<?php

namespace app\common\controller;

use think\Request;
use think\Response;
use think\exception\HttpResponseException;

class ApiBase
{
    public $user = null;
    
	/**
     * 构造函数
     * 
     */
    public function __construct()
    {
        // 允许跨域
        $origin  = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authToken");

        if (! cache('sys_config')) {
            $list = \think\Db::name('config')->column('key,value');
		    cache('sys_config', $list);
        }

        config(cache('sys_config'));

        $this->_initialize();
    }
    
    /**
     * 初始化
     *
     * @return void
     */
    public function _initialize()
    {
        if (! config('app_status')) {
            $this->error('no access');
        }
        
        $request = Request::instance();

        if ($request->isOptions()) {
            $this->success();
        }
        
        if (! config('WEB_STATUS')) {
            $this->error('系统维护中，暂停登录！');
        }

        $header = $request->header();
        
        if (isset($header['authtoken'])) {
            $authToken = explode(':', $header['authtoken']);
        } else {
            $this->error('no access' . __LINE__, 401);
        }
        
        $this->user = \think\Db::name('user')
            ->where("tel", $authToken[0])
            ->field('uid,is_shop,is_agent,name,tel,pwd,s_pwd,status')->find();
        if (empty($this->user)) {
            $this->error('用户信息不存在');
        }

        if (! $this->user['status']) {
            $this->error('此账号已冻结');
        }

        $password = $this->user['pwd'];
        
        $dataStr = $this->jsDecrypt($authToken[1], $password);
        if (empty($dataStr)) {
            $this->error('no access' . __LINE__, 401);
        }

        $dataStr = explode(':', $dataStr);

        if ($dataStr[0] != $_SERVER['REQUEST_URI']) {
           $this->error('账户信息不正确');
        }

        // $rqsTime = substr($dataStr[1], 0, 10);
        // if ($rqsTime + config('token_valid_time') > $request->time()) {
        //     $this->error('no access' . __LINE__, 401);
        // }
    }  

    /**
     * 权限验证
     * 
     * @param  [type] $name [description]
     * @param  [type] $uid  [description]
     * @return [type]       [description]
     */
    public function checkAuth($name, $uid)
    {
        $auth = new Auth();  

        return $auth->check($name, $uid);
    }

    /**
     * 解密token数据
     *
     * @param [type] $encryptedData
     * @param [type] $privateKey
     * @param string $iv
     * @return void
     */
    private function jsDecrypt($encryptedData, $privateKey, $iv = "O2%=!ExPCuY6SKX(")
    {
        $encryptedData = base64_decode($encryptedData);
        // mcrypt_decrypt php7.1以后，不建议用
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);

        $decrypted = rtrim($decrypted, "\0");

        return $decrypted;
    }

    /**
     * 返回API数据到客户端
     *
     * @param [type] $data
     * @param integer $code
     * @param string $msg
     * @param string $type
     * @param array $header
     * @return void
     */
    protected function result($data, $code = 200, $msg = 'success', $type = 'json', array $header = [])
    {
        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
            'time' => date('Y-m-d H:i:s', Request::instance()->server('REQUEST_TIME')),
        ];
        
        $response = Response::create($result, $type, $code)->header($header);

        throw new HttpResponseException($response);
    }

    /**
     * 自定义信息
     * 
     * @param  string $msg [description]
     * @return [type]           [description]
     */
    public function success($msg = '', $code = 200, $type = 'json')
    {
        if (is_array($msg)) {
            $result = $msg;
        } else {
            $result = [
                'code' => 1,
                'msg'  => $msg,
                'data' => '',
            ];
        }
        
        $response = Response::create($result, $type, $code);

        throw new HttpResponseException($response);
    }

    /**
     * 错误信息
     * 
     * @param  string $errorMsg [description]
     * @return [type]           [description]
     */
    public function error($errorMsg = '', $code = 200, $type = 'json')
    {
        $result = [
            'code' => 0,
            'msg'  => $errorMsg,
            'data' => '',
        ];
        
        $response = Response::create($result, $type, $code);

        throw new HttpResponseException($response);
    }
}